package com.linck.im.server.initial;

import com.linck.im.model.proto.ProtoMsg;
import com.linck.im.parse.decode.PackageDecode;
import com.linck.im.parse.encode.PackageEncode;
import com.linck.im.server.handler.ServeHeartBeatHandler;
import com.linck.im.server.handler.ServerLoginInfoHandler;
import com.linck.im.server.handler.ServerMessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;


/**
 * @author: linck
 * @create: 2021-01-25
 */
public class ChatServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // tcp拆包粘包处理
        pipeline.addLast(new LengthFieldPrepender(2));
        pipeline.addLast(new ProtobufEncoder());
        pipeline.addLast(new PackageEncode());

        // tcp拆包粘包处理
        pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
        pipeline.addLast(new ProtobufDecoder(ProtoMsg.Package.getDefaultInstance()));
        pipeline.addLast(new PackageDecode());
        // 心跳检测 读空闲15s，触发userEventTriggered
        pipeline.addLast(new IdleStateHandler(15, 0, 0, TimeUnit.SECONDS));
        pipeline.addLast(new ServeHeartBeatHandler());
        pipeline.addLast(new ServerMessageHandler());
        pipeline.addLast(new ServerLoginInfoHandler());
    }
}
